// pages/aiindex/aiChat/aiChat.js
// pages/aiindex/indexDesc/indexDesc.js
var api = require('../../utils/api')
var socketStatus = 'closed'
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        dialogueId: 0,
        dialogue_list: [],
        open: false,
        answer_loading: false,
        answerDesc: '',
        typePage: 'AI聊天',
        title: '',
        pageNum: 1,
        pageSize: 5,
        loading: true,
        scrollTop: 0,
        beginTitle: '您好，欢迎使用996的幻码帕鲁AI聊天系统',
        beginTips: '我是一名智能聊天AI机器人，能给你的996生活带来很多帮助，早点下班哦',
        beginList: [
            {id: 1, tips: '请用java帮我写个简单的冒泡排序'},
            {id: 2, tips: '如何避免996'},
            {id: 3, tips: '中午吃什么？'},
        ],
        chatList: [],
        isPageClosed: false,
        isTyping: false, // 是否正在显示消息
        typingContent: '', // 当前正在显示的消息内容
        isThisChatOver: true, //本轮对话是否结束
        overFlag: 'THIS_CHAT_OVER', // 结束标识
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        this.setData({
            newMessageQueue: [], // 初始化消息队列
        });
    },
    showTypingContent() {
        if (!this.data.typingContent || this.data.isTyping || this.data.typingContent === this.data.overFlag) {
            this.setData({
                isTyping: false,
                typingContent: '', // 清空当前内容
                isThisChatOver: true
            });
            return;
        } // 如果没有内容或者正在显示则返回

        this.setData({
            isTyping: true,
        });

        let index = 0;
        let currentMessage = this.data.answerDesc;
        const typingInterval = setInterval(() => {
            if (index < this.data.typingContent.length) {
                this.setData({
                    answerDesc: currentMessage + this.data.typingContent.slice(0, ++index),
                });
                this.autoScroll()
            } else {
                clearInterval(typingInterval);
                this.setData({
                    isTyping: false,
                    typingContent: '', // 清空当前内容，准备下一条消息
                });
                // 检查是否有新的消息需要显示
                if (this.data.newMessageQueue.length > 0) {
                    const nextMessage = this.data.newMessageQueue.shift(); // 取出队列中的第一条消息
                    this.setData({
                        typingContent: nextMessage,
                    });
                    this.showTypingContent(); // 递归调用自己，显示下一条消息
                }
            }
        }, 50); // 每80毫秒显示一个字符，可按需调整
    },

    connectSocket(){
        const that = this;
        const {loginToken} = wx.getStorageSync('userLogin');
        if(loginToken==null){
           return
        }
        const url = api.ws_url+loginToken;
        console.log('url',url);
        wx.connectSocket({
            url: url,
            header:{
                'content-type': 'application/json'
            },
            success: ()=>{
                console.log('成功连接');
            }
        })
        wx.onSocketOpen((result) => {
            console.log('socket打开成功');
            socketStatus = 'connected'
        })
        wx.onSocketClose(()=>{
            socketStatus = 'closed'
            that.reconnect()
        })
        wx.onSocketMessage((result) => {
            if (result.data) {
                console.log(result.data)
                this.setData({
                    answer_loading: true,
                    newMessageQueue: [...this.data.newMessageQueue, result.data], // 将新消息加入队列
                });

                // 如果当前没有正在显示的消息，开始显示队列中的消息
                if (!this.data.isTyping) {
                    this.setData({
                        typingContent: this.data.newMessageQueue.shift(), // 取出队列中的第一条消息
                    });
                    this.showTypingContent();
                }
            }
            // // console.log('onSocketMessage',result.data);
            // if(result.data){
            //     that.setData({
            //         answer_loading: true,
            //         answerDesc: result.data,
            //         answerContentFormat: towxmlFun(result.data, "markdown")
            //     })
            //     that.autoScroll()
            // }

        })
    },
    reconnect(){
        console.log("isPageClosed:"+this.data.isPageClosed)
        if(this.data.isPageClosed){
            return
        }
        let timer = null;
        if(socketStatus == 'closed'){
            timer && clearTimeout(timer);
            timer = setTimeout(()=>{
                this.connectSocket()
            },3000)
        }
        // else {
        //     this.closeSocket()
        // }
    },
    closeSocket(){
        const that = this;
        that.setData({
            isPageClosed: true
        })
        if(socketStatus == 'connected'){
            wx.closeSocket({
                success: ()=>{
                    socketStatus = 'closed'
                }
            })
        }
    },
    //列表的操作函数
    open_chat: function(opts){
        const that = this;
        that.setData({
            chatList: [],
            pageNum: 1,
            loading: true,
            dialogueId: opts.currentTarget.dataset.id,
            open: false,
            answerDesc: '',
            answer_loading: false,
            typePage: opts.currentTarget.dataset.title || 'AI',
        });
        this.getHistoryList();

    },
    del_chat(opts){
      // opts.currentTarget.dataset.id
      const that = this
      if(that.data.dialogueId == opts.currentTarget.dataset.id){
        wx.showToast({
          title: '该会话正在进行中，不可删除',
          icon: 'none'
        })
        return
      }
        const config = {
            url: api.dialogue_del_url + opts.currentTarget.dataset.id,
            method: 'DELETE',
            data: {}
        }
        api.getRequest(config).then(res => {
            if (res) {
                that.getchatIdList()
            }
        })
    },
//  新建对话
    creatChat: function(){
        const that = this;
        that.setData({
            chatList: [],
            answerDesc: "",
            pageNum: 1,
            loading: true,
            dialogueId: 0
        });
        //其实清空dialogueId就行了
        that.cancelChat()
        // that.openAndSend(()=>{
        // that.cancelChat()
        // })
        // const config = {
        //     url: api.creatDialogue_url,
        //     method: 'POST',
        //     data: {}
        // }
        // api.getRequest(config).then(res=>{
        //     if(res){
        //         // that.getchatIdList()
        //         that.cancelChat()
        //         that.openAndSend()
        //     }
        // })
    },
    // 关闭弹窗
    cancelChat(){
      const that = this
      that.setData({
        open: false
      })
    },
    //左侧导航的开关函数
    openAddChat: function(){
        // this.data.open ? this.setData({open: false}) :this.setData({open: true});
        if(this.data.open){
            this.cancelChat()
            return
        }
        this.setData({open: true});
        this.getchatIdList()
    },
    autoScroll() {
        let that = this
        let query = wx.createSelectorQuery()
        // 通过class选择器定位到scorll-view
        query.select('.scroll-text').boundingClientRect(res => {
            that.setData({
                // 由于res.height效果不明显，所以乘以100系数，这个系数可以根据实际效果调整
                scrollTop: res.height * 100
            })
        })
        query.exec(res => {})
    },
    getchatIdList(){
        const that = this;
        const config = {
            url: api.dialogue_url,
            method: 'POST',
            data: {
                pageNum: 1,
                pageSize: 20,
            }
        }
        api.getRequest(config).then(res=>{
            // res
            if(res.rows){
                that.setData({
                    dialogue_list: res.rows
                })
            }
        })
    },
    getHistoryList(){
        const that = this;
        if(!that.data.loading){
            return
        }
        const config = {
            url: api.chat_url,
            method: 'POST',
            data: {
                dialogueId: that.data.dialogueId || 0,
            }
        }
        api.getRequest(config).then(res=>{
            that.setData({
                loading: false,
                chatList: [...res.data, ...that.data.chatList],
            })
            that.autoScroll()
        });
    },
    beginChatSend(opts){
        const that = this;
        that.setData({
            title: opts.currentTarget.dataset.title,
        });
        that.sendChat();
    },
    bindblur(event){
        const that = this
        that.setData({
            title: event.detail.value,
        });
        // that.sendChat();
    },
    async openAndSend(callback){
      const that = this
      that.setData({
        chatList: [],
        answerDesc: "",
        pageNum: 1,
        loading: true,
    });
    const config = {
        url: api.creatDialogue_url,
        method: 'POST',
        data: {}
    }
    api.getRequest(config).then(res=>{
        if(res.data){
          that.setData({
            dialogueId: res.data
          })
          callback && callback()

        }
    })
      // that.sendChat();
    },

   async sendChat(){
        const that = this;
        // chatpost_url
        if(!that.data.title){
            wx.showToast({
                title: '请输入内容',
                icon: 'none'
            })
            return
        }
       if(!that.data.isThisChatOver){
           wx.showToast({
               title: '本轮对话结束后再发送',
               icon: 'none'
           })
           return
       }
        if(!that.data.dialogueId){
          that.openAndSend(()=>{
            that.sendChat();
          })
          return
        }
        if(that.data.chatList.length<=0){
          that.setData({
            typePage: that.data.title || 'AI'
          })
        }
       that.setData({
           isThisChatOver: false,
       });
        const config = {
            url: api.chatpost_url,
            method: 'POST',
            data: {
                dialogueId: that.data.dialogueId || 0,
                content: that.data.title,
            }
        }
        //阻塞获取请求结果
       try {
           const send = await api.getRequest(config);
           console.log("send.data ", send.data);

       } catch (e) {
           console.log("waitSendChat error ", e);
           return;
       }
       if(that.data.answerDesc){
        that.setData({
            chatList: [ ...that.data.chatList,{
                role: 'assistant',
                content: that.data.answerDesc}],
        });
    }
    that.setData({
        chatList: [ ...that.data.chatList,{
            role: 'user',
            content: that.data.title}],
    });

    that.setData({
      answer_loading: false,
      answerDesc: ''
  })
    that.autoScroll()
    that.setData({
        title: '',
    });

    },

    async waitSendChat(config) {
        try {
            const send = await api.getRequest(config);
            console.log("send.data ", send.data);
            return true;
        } catch (e) {
            console.log("waitSendChat error ", e);
            return false;
        }
    },

    copyChatContent(e) {
        const { dataset } = e.currentTarget;
        const { content } = dataset;

        wx.setClipboardData({
            data: content,
            success() {
                wx.showToast({ title: '复制成功', icon: 'success' });
            },
            fail(err) {
                console.error('Failed to copy:', err);
                wx.showToast({ title: '复制失败', icon: 'none' });
            },
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.connectSocket();
        this.getTabBar().init();
        const cachedTheme = wx.getStorageSync('currentTheme');
        if (cachedTheme) {
            app.onThemeChange(cachedTheme);
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        console.log('onHide')
        this.closeSocket();
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        console.log('onUnload')
        this.closeSocket();
        this.setData({
            isTyping: false,
            typingContent: '',
            newMessageQueue: [],
        });
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})
